package com.wonders.demo.controller;


import com.alibaba.fastjson.JSONObject;
import com.wonders.demo.util.HttpUtils;
import com.wonders.demo.util.SignUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author wangjian
 * @date 2019/03/20
 * describe:
 */
@Controller
public class TestController {


    @Value("${oauth2.code.url}")
    private String getTokenUrl;
    @Value("${oauth2.token.url}")
    private String getUserMsgUrl;

    //应用私钥
    @Value("${app.private.key}")
    private String appPrivateKey;

    @GetMapping("login")
    public String login(){
        return "login";
    }


    /**
     * 获取用户信息
     *
     * @param code
     * @param client_id 租户信息
     * @param redirect_uri 回调接口
     * @return
     */
    @RequestMapping("/getUserMsg")
    @ResponseBody
    public String getUser(String code, String client_id, String redirect_uri, String isEncrypt, String tgt) {
        JSONObject ret = new JSONObject();
        //使用treeMap来帮我们排序
        Map<String, Object> params = new TreeMap<>();
        params.put("code", code);
        params.put("client_id", client_id);
        params.put("redirect_uri", redirect_uri);
        params.put("isEncrypt", 0);
        //拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : params.keySet()) {
            stringBuilder.append(key).append("=").append(params.get(key)).append("&");
        }
        //加签内容
        String content = stringBuilder.toString().substring(0, stringBuilder.length() - 1);
        System.out.println("加签内容："+content);
        //将内容进行签名
        String sign = SignUtils.sign(content, appPrivateKey);
        System.out.println("生成签名："+sign);
        params.put("sign", sign);
        try {
            //拿code换区token
            System.out.println("获取token地址："+getTokenUrl+"?client_id="+client_id+"&code="+code+"&isEncrypt=0&sign="+sign);
            JSONObject result = (JSONObject) HttpUtils.syncPost2(getTokenUrl, params, tgt);
            System.out.println("获取token结果："+result.get("message"));
            if (result.getInteger("code") == 200) {
                String token = result.getJSONObject("data").getJSONObject("content").getString("token");
                //通过token获取用户信息
                JSONObject data = getToken(token, client_id, redirect_uri, tgt);
                //封装返回
                if (data != null && data.size() > 1) {
                    ret.put("code", 200);
                    ret.put("data", data);
                    return ret.toString();


                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ret.put("code", 500);
        return ret.toString();
    }

    /**
     * token换用户信息
     *
     * @param token
     * @param client_id
     * @param redirect_uri
     * @return
     */
    public JSONObject getToken(String token, String client_id, String redirect_uri, String tgt) {
        Map<String, Object> params = new TreeMap<>();
        params.put("access_token", token);
        params.put("client_id", client_id);
        params.put("redirect_uri", redirect_uri);
        params.put("isEncrypt", 0);

        //拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : params.keySet()) {
            stringBuilder.append(key).append("=").append(params.get(key)).append("&");
        }
        //加签
        String sign = stringBuilder.toString().substring(0, stringBuilder.length() - 1);
        System.out.println(sign);
        System.out.println("sign:" +SignUtils.sign(sign, appPrivateKey));
        params.put("sign", SignUtils.sign(sign, appPrivateKey));

        try {
            //调用token换用户信息的接口
            JSONObject result = (JSONObject) HttpUtils.syncPost(getUserMsgUrl, params, tgt);
            System.out.println(result.toJSONString());
            if (result.getInteger("code") == 200) {
                        return result.getJSONObject("data");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("getCode")
    @ResponseBody
    public JSONObject getCode(String tgt) throws Exception {
        JSONObject ret = new JSONObject();
        //使用treeMap来帮我们排序
        Map<String, Object> params = new TreeMap<>();
        params.put("client_id", "dbb8b982ad154f699805914b0a4c79a5");
        params.put("redirect_uri", "http://wonders.liuzhou.gov.cn/budongchan");
        params.put("isEncrypt", 0);
        //拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : params.keySet()) {
            stringBuilder.append(key).append("=").append(params.get(key)).append("&");
        }
        //加签
        String si = stringBuilder.toString().substring(0, stringBuilder.length() - 1);
        String sign = SignUtils.sign(si, appPrivateKey);
        params.put("sign", sign);
        JSONObject result = (JSONObject) HttpUtils.syncPost("http://wonders.liuzhou.gov.cn/oauth2/app/agree", params, tgt);
        return result;
    }

    @GetMapping("loginMsg")
    @ResponseBody
    public JSONObject loginMsg(HttpServletRequest request) throws Exception {
        JSONObject ret = new JSONObject();
        HashMap<String, Object> map = new HashMap<>();
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            Object object = (Object) e.nextElement();
            map.put(object.toString(), request.getParameter(object.toString()));
        }

        System.out.println(map);
        return ret;
    }

}
